package org.note.law.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.jpa.utils.JpaDataUtil;
import org.note.law.domain.MarkdownNode;
import org.note.law.module.law.LawCode;
import org.note.law.module.law.LawCodeService;
import org.note.law.module.law.params.LawCodeParams;
import org.note.law.module.law.params.LawCodeQueryParams;
import org.note.law.module.provision.LawProvision;
import org.note.law.module.provision.LawProvisionService;
import org.note.law.utils.MarkdownParser;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("law")
@Api(tags = "法典管理")
@AllArgsConstructor
public class LawCodeController {
    LawCodeService service;

    LawProvisionService provisionService;
    @SneakyThrows
    @PostMapping("codes")
    @ApiOperation(value = "法典新建/更新")
    public ResponseDTO<Object> codeSet(@Validated LawCodeParams params){
        MultipartFile file = params.getFile();
        if (file.isEmpty()) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST, "上传文件不可为空");
        }

        StringBuilder contentSb = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentSb.append(line).append("\n");
            }
        }
        String content = contentSb.toString();
       // log.info(content);
        MarkdownNode node = MarkdownParser.parse(content);
        // 构建法典信息
        LawCode code = new LawCode();
        // 提取Meta
        String meta = node.getContent();
        String[] lines = meta.split("\n");
        for (String line : lines) {
            // 包含部分处理
            if (line.contains(":")){
                String[] keyValue = line.split(":", 2); // 只分割第一个冒号
                String key = keyValue[0];
                if (key.equals("版本")){
                    code.setCodeVersion(keyValue[1]);
                }
                if (key.equals("封面")){
                    code.setCodeCover(keyValue[1]);
                }
                if (key.equals("介绍")){
                    code.setCodeDesc(keyValue[1]);
                }
                if (key.equals("名称")){
                    code.setCodeName(keyValue[1]);
                }
            }

        }
        List<LawProvision> provisions = new ArrayList<>();
        // MarkdownParser.printTree(node, "");
        MarkdownParser.flattenTreeHelper(node, provisions);
        List<LawCode> codes = service.getByCodeNameAndCodeVersion(code.getCodeName(), code.getCodeVersion());
        // 如果不为空
        if (!codes.isEmpty()){
            // 删除已有的
            LawCode oldCode = codes.get(0);
            String oldCodeId = oldCode.getId();
            provisionService.deleteByCodeId(oldCodeId);
            service.deleteOne(oldCodeId);
        }
        code.setContent(content);
        LawCode result = service.saveOne(code);
        // 根据法典结果写入
        String resultCodeId = result.getId();
        String resultCodeName = result.getCodeName();
        String resultCodeVersion = result.getCodeVersion();
        provisions = provisions.stream().peek(ele->{
            ele.setCodeId(resultCodeId);
            ele.setCodeName(resultCodeName);
            ele.setCodeVersion(resultCodeVersion);
        }).collect(Collectors.toList());
        // 写入
        provisionService.batchSave(provisions);
        // log.info(String.valueOf(content));
        return ResponseDTO.succData(result);
    }


    @DeleteMapping("codes/{id}")
    @ApiOperation(value = "法典删除")
    public ResponseDTO<Object> codeDelete(@PathVariable("id") String id){
        // 查询判断是否为最新
        provisionService.deleteByCodeId(id);
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }



    @SneakyThrows
    @GetMapping("codes")
    @ApiOperation(value = "法典列表")
    public ResponseDTO<Object> codeList(LawCodeQueryParams params){
        Pageable pageable = JpaDataUtil.buildPageable(params);
        // 构建Example查询
        LawCode lawCode = new LawCode();
        BeanUtil.copyProperties(params, lawCode);
        String key = params.getSearchKey();
        if (Validator.isEmpty(key)){
            return ResponseDTO.succData(
                    service.getAllIgnoreFile(pageable)
            );
        }
        return ResponseDTO.succData(
                service.getAllMatcher(pageable, key)
        );
    }

    @SneakyThrows
    @GetMapping("codes/{id}")
    @ApiOperation(value = "法典查询")
    public ResponseDTO<Object> codeQuery(@PathVariable("id") String id){
        LawCode code = service.getOneUnwrap(id);
        // 获取内容
        String content = code.getContent();
        // log.info(content);
        MarkdownNode node = MarkdownParser.parse(content);
        Map<String, Object> resultMap = BeanUtil.beanToMap(code);
        resultMap.remove("content");
        resultMap.put("menu", node);
        return ResponseDTO.succData(resultMap);
    }


    @SneakyThrows
    @GetMapping("codes/{id}/cates/{title}")
    @ApiOperation(value = "法典法条查询")
    public ResponseDTO<Object> codeProvisionQuery(@PathVariable("id") String id,@PathVariable("title") String title){
        LawCode code = service.getOneUnwrap(id);
        // 获取内容
        String content = code.getContent();
        // log.info(content);
        MarkdownNode node = MarkdownParser.parse(content);
        List<LawProvision> provisions = new ArrayList<>();
        // MarkdownParser.printTree(node, "");
        MarkdownParser.flattenTreeHelper(node, provisions);
        int matchIdx = 0;
        int len = provisions.size();
        for (int i = 0; i < len; i++){
            LawProvision provision = provisions.get(i);
            if (provision.getTitle().equals(title)){
                matchIdx = i;
                break;
            }
        }
        LawProvision provision = provisions.get(matchIdx);
        provision.setCodeId(code.getId());
        provision.setCodeName(code.getCodeName());
        provision.setCodeVersion(code.getCodeVersion());
        if (Validator.isEmpty(provision.getContent())){
            provision.setContent("内容待补充");
        }
        Map<String , Object> resultMap = BeanUtil.beanToMap(provision);
        resultMap.put("pre",matchIdx > 1 ? provisions.get(matchIdx - 1).getTitle() : null);
        resultMap.put("next", matchIdx < len - 1 ? provisions.get(matchIdx + 1).getTitle() : null);
        // 查询是否收藏
        resultMap.put("marked", false);
        return ResponseDTO.succData(resultMap);
    }
}
